package com.gict.antifraudback.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Service
public class ImageDownloader {

    // 设置请求参数，并对查询参数进行 URL 编码
    public static String configs(String search, int page) throws UnsupportedEncodingException {
        String encodedSearch = URLEncoder.encode(search, "UTF-8");
        return String.format(
                "https://image.baidu.com/search/acjson?tn=resultjson_com&logid=11555092689241190059&ipn=rj&ct=201326592&queryWord=%s&word=%s&pn=%d&rn=%d&gsm=1e",
                encodedSearch, encodedSearch, 30 * page, 30);
    }

    // 加载图片链接并返回
    public static List<String> collectPicLinks(String search, int page, int toPage) throws IOException {
        HttpClient client = new HttpClient();
        List<String> urlList = new ArrayList<>();

        while (page <= toPage) {
            String url = configs(search, page);
            HttpMethod method = new GetMethod(url);
            method.getParams().setParameter(HttpMethodParams.USER_AGENT,
                    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36");

            try {
                client.executeMethod(method);
                String response = method.getResponseBodyAsString();

                // 使用 fastjson 解析 JSON 响应
                JSONObject jsonResponse = JSON.parseObject(response);
                JSONArray dataArray = jsonResponse.getJSONArray("data");

                urlList.addAll(getUrlList(dataArray));
                page++;
            } finally {
                method.releaseConnection();
            }
        }
        return urlList;
    }

    // 获取图片 URL 列表
    private static List<String> getUrlList(JSONArray dataArray) {
        List<String> urlList = new ArrayList<>();
        for (int i = 0; i < dataArray.size() - 1; i++) {
            JSONObject data = dataArray.getJSONObject(i);
            if (data.containsKey("thumbURL")) {
                urlList.add(data.getString("thumbURL"));
            }
        }
        return urlList;
    }

    // 下载图片
    public static void getImg(String imgUrl, int idx, String path, String enName) throws IOException {
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod(imgUrl);

        File file = new File(path);
        if (!file.exists()) {
            file.mkdir();
        }

        method.getParams().setParameter(HttpMethodParams.USER_AGENT,
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36");

        try {
            client.executeMethod(method);
            InputStream inputStream = method.getResponseBodyAsStream();

            // 保存图片到本地
            try (FileOutputStream fos = new FileOutputStream(path + enName + "_" + (idx + 1) + ".jpg")) {
                byte[] buffer = new byte[1024];
                int len;
                while ((len = inputStream.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                }
            }

        } finally {
            method.releaseConnection();
        }
    }

    // 使用多线程下载图片
    public static void downloadImages(List<String> urlList, String path, String enName) {
        // 创建线程池
        ExecutorService executor = Executors.newFixedThreadPool(10);  // 10个线程
        int idx = 0;

        for (String url : urlList) {
            int finalIdx = idx;
            executor.submit(() -> {
                try {
                    getImg(url, finalIdx, path, enName);
                    System.out.println("下载图片: " + (finalIdx + 1));
                } catch (IOException e) {
                    System.err.println("下载图片出错: " + e.getMessage());
                }
            });
            idx++;
        }

        // 关闭线程池，等待所有任务完成
        executor.shutdown();
        try {
            executor.awaitTermination(1, TimeUnit.MINUTES);  // 最长等待1分，等待线程结束
        } catch (InterruptedException e) {
            System.err.println("线程中断: " + e.getMessage());
        }
    }

    public static void main(String[] args) {
        String search = "空气开关"; // 关键字
        String enName = "空气开关"; // 保存的文件前缀

        String path = "D:\\dowload\\"+ search +"\\";

        try {
            // 第一步：收集图片链接  下载0-20页  每页是30张
            List<String> urlList = collectPicLinks(search, 0, 20);
            System.out.println("收集到的图片链接数量: " + urlList.size());

            // 第二步：使用多线程下载图片
            downloadImages(urlList, path, enName);
        } catch (IOException e) {
            System.out.println("发生错误: " + e.getMessage());
        }
    }

}
